<template>
  <div class="app-container">
    <div style="float:right;">
    <el-radio-group v-model="msgTab" @change="getList">
      <el-radio-button label="1">未读消息</el-radio-button>
      <el-radio-button label="2">已读消息</el-radio-button>
      <el-radio-button label="3">我发出的消息</el-radio-button>
    </el-radio-group>
  </div>
  <br />
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发送时间" prop="send_time">
        <el-date-picker
          v-model="queryParams.send_time"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sys:msg:add']"
        >发消息</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sys:msg:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['sys:msg:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="msgList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="类别" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_msg_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="发送人" align="center" prop="nick_name" v-if="msgTab !='3'"/>
      <el-table-column label="接收人" align="center" prop="nick_name" v-if="msgTab =='3'"/>
      <el-table-column label="发送时间" align="center" prop="send_time" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.send_time, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="链接地址" align="center" prop="url">
        <template slot-scope="scope">
          <router-link :to="{path:scope.row.url}" v-if="scope.row.url">点击</router-link>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column label="是否已读" align="center" prop="is_read" v-if="msgTab =='3'">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.is_read"/>
        </template>
      </el-table-column>
      <el-table-column label="阅读时间" align="center" prop="read_time" width="180" v-if="msgTab !='1'">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.read_time, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="msgTab != '3' && scope.row.type != '1'"
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleUpdate(scope.row, 'reply')"
          >回复</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleUpdate(scope.row, 'read')"
          >打开</el-button>
          <el-button v-if="scope.row.is_read == 'Y'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="pager.page"
      :limit.sync="pager.limit"
      @pagination="getList"
    />
    <!-- 添加或修改系统消息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" v-show="formAction == 'send'"/>
            <span v-text="form.title" v-show="formAction != 'send'"/>
          </el-form-item>
          <el-form-item label="内容">
            <editor v-model="form.content" :min-height="192" v-show="formAction == 'send'"/>
            <span v-html="form.content" v-show="formAction != 'send'"/>
          </el-form-item>
          <el-form-item label="接收人" prop="to_user_id" v-if="formAction == 'send'">
            <el-select v-model="form.to_user_id" placeholder="请选择审核人" clearable>
              <el-option
                v-for="u in userOptions"
                :key="u.value"
                :label="u.label"
                :value="u.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="链接地址" prop="url" v-if="form.type == '1' && form.url">
            <router-link :to="{path:form.url}">点击</router-link>
          </el-form-item>
        <el-form-item label="回复内容" v-if="formAction == 'reply'">
          <editor v-model="form.replyContent" :min-height="192"/>
        </el-form-item>
      </el-form>
        
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="formAction == 'read' && msgTab =='1'">标记已读</el-button>
        <el-button type="primary" @click="submitForm" v-if="formAction == 'send'">发送</el-button>
        <el-button type="primary" @click="submitForm" v-if="formAction == 'reply'">回复</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { apiGet, apiPost, apiPatch, apiDelete, apiDs, apiExport, apiDownload } from "@/api/openapi";

export default {
  name: "Msg",
  dicts: ['sys_msg_type', 'sys_yes_no'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 系统消息表格数据
      msgList: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      msgTab: '1',
      queryParams: {
        type: null,
        title: null,
        pid: null,
        from_user_id: null,
        send_time: null,
        is_read: null,
        "@table": "sys_msg",
        "@exp": {
      // 阅读时间模糊搜索
      title: 'lk',
      send_time: 'bt',
        }
      },
      pager: {
        page: 1,
        limit: 10,
        order: "id desc",
      },
      // 导入参数
      upload: false,
      userOptions:[],
      // 表单参数
      form: {},
      formAction: null,
      // 表单校验
      rules: {
        type: [
          { required: true, message: "类别不能为空", trigger: "change" }
        ],
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        to_user_id: [
          { required: true, message: "接收人不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    apiDs('sys_user_select').then(response=>{
        this.userOptions = response.data;
    });
  },
  methods: {
    /** 查询系统消息列表 */
    getList() {
      this.loading = true;
      let params = {"@pager": this.pager, "t":{ ...this.queryParams}};
      if(this.msgTab == '1'){
        params['t']['is_read'] = 'N';
        params['t']['to_user_id'] = '@userId()';
        params['u'] = {"@table":"sys_user", "@join":"u.user_id = t.from_user_id", "@column":'nick_name'};
      }else if(this.msgTab == '2'){
        params['t']['to_user_id'] = '@userId()';
        params['u'] = {"@table":"sys_user", "@join":"LEFT u.user_id = t.from_user_id", "@column":'nick_name'};
      }else if(this.msgTab == '3'){
        params['t']['from_user_id'] = '@userId()';
        params['u'] = {"@table":"sys_user", "@join":"u.user_id = t.to_user_id", "@column":'nick_name'};
      }
      apiGet(params).then(response => {
        this.msgList = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: '2',
        title: null,
        content: null,
        pid: null,
        from_user_id: '@userId()',
        to_user_id: null,
        nick_name: null,
        send_time: '@now()',
        url: null,
        is_read: 'N',
        read_time: null,
        replyContent: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.pager.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.send_time = [];
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.formAction = 'send';
      this.open = true;
      this.title = "添加系统消息";
    },
    /** 修改按钮操作 */
    handleUpdate(row, formAction) {
      this.reset();
      this.formAction = formAction;
      const id = row.id || this.ids
        let data = {"t":{"@table":"sys_msg", id:id}};
        
      if(this.formAction == 'read' || this.formAction == 'reply'){
        data['u'] = {"@table":"sys_user", "@join":"LEFT u.user_id = t.from_user_id", "@column":'nick_name'};
      }else if(this.msgTab == '3'){
        data['t']['from_user_id'] = '@userId()';
        data['u'] = {"@table":"sys_user", "@join":"u.user_id = t.to_user_id", "@column":'nick_name'};
      }
      apiGet(data).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "查看系统消息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let data = {
            'sys_msg': [],
            '@tags': ['sys_msg']
          };
          if(this.formAction == 'read'){
            this.form.is_read = 'Y';
            this.form.read_time = '@now()';
            data['sys_msg'].push(this.form);
          }else if(this.formAction == 'reply'){
            if(this.form.is_read == 'N'){
               this.form.is_read = 'Y';
              this.form.read_time = '@now()';
              data['sys_msg'].push(this.form);
            }
            data['sys_msg'].push({
              id: null,
              type: '2',
              title: '[回复]' + this.form.title,
              content: this.form.replyContent,
              pid: this.form.id,
              from_user_id: '@userId()',
              to_user_id: this.form.from_user_id,
              send_time: '@now()',
              url: null,
              is_read: 'N',
              read_time: null    
            });
          }else{            
            data['sys_msg'].push(this.form);
          }
          apiPatch(data).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中的系统消息数据？').then(function() {
        let data = {};
        data['sys_msg'] = { id:ids, "@exp":{id:"in"}};
        data['@tags'] = ['sys_msg'];
        return apiDelete(data);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
        let params = {};
      params['sys_msg'] = {...this.queryParams};
      params['@pager'] = {page:1, limit:10000};
      apiExport(params).then(response => {
        apiDownload(response.msg);
      });
    }
  }
};
</script>
